<template>
  <div class="video-extraction-index">
    <div class="flex justify-between" style="height: 64px; align-items: center">
      <div>
        <RouteTitle :isBack="true" />
      </div>
      <a-button type="primary" @click="jumpPath('VideoRemoveSignList')"
        >操作记录</a-button
      >
    </div>
    <div class="video-extraction-body">
      <div class="video-extraction-left">
        <template v-if="!videoUrl">
          <a-form layout="horizontal">
            <a-form-item label="视频来源">
              <a-radio-group v-model:value="radioValue">
                <a-radio :value="1"> 网络视频 </a-radio>
                <a-radio :value="2"> 素材库视频 </a-radio>
              </a-radio-group>
            </a-form-item>
            <div class="tip text-gray-5" v-if="radioValue == 1">
              输入视频分享链接，一键智能视频解析，提取视频。支持平台：{{pList.join('、')}}。
            </div>
            <a-form-item label="视频链接" v-if="radioValue == 1">
              <a-textarea
                v-model:value="internetVideoUrl"
                placeholder="请粘贴抖音视频链接，视频时长建议不超过20分钟"
                style="
                  width: 800px;
                  height: 160px;
                  resize: none;
                  border-radius: 5px;
                "
              >
              </a-textarea>
            </a-form-item>
            <a-form-item label="视频素材" v-if="radioValue == 2">
              <a-card v-if="!currentVideo?.material_url">
                <div class="upload-wrapper">
                  <div class="upload-content" @click="debouncedClick">
                    <cloud-upload-outlined />
                    <span class="text-16 text-gray-5">添加视频</span>
                  </div>
                </div>
              </a-card>
              <div class="video_con" v-else>
                <video
                  id="videoPlayer"
                  :src="currentVideo?.material_url"
                  autoplay
                />
                <div class="operate_con">
                  <cu-icon
                    @click="deleteVideo"
                    type="icon-shanchu1"
                    class="delete_icon"
                  />
                </div>
              </div>
            </a-form-item>
          </a-form>
          <div style="margin-left: 70px;color:#666" v-if="radioValue == 1 || radioValue == 2 && currentVideo?.material_url">
            <a-button
              type="primary"
              :loading="submitLoading"
              @click="handleExtract"
              >{{ btnTxt }}</a-button
            >
            <div class="mt-5">
              当前剩余{{ name_unit }}{{ residue_count
              }}{{ unit }},（每次提取消耗{{ consumes }}{{ unit
              }}{{ name_unit }} ）
            </div>
          </div>
        </template>
        <VideoRemoveSign
          v-else
          :videoUrl="videoUrl"
          :loading="cropLoading"
          @cancelCrop="cancelCrop"
          @startCrop="handleCrop"
        ></VideoRemoveSign>
      </div>

      <div class="video-extraction-right">
        <template v-if="!cropLoading">
          <template v-if="cropVideoUrl">
            <div class="video-wrap">
              <video
                style="height: 100%; width: 100%"
                controls
                :src="cropVideoUrl"
              ></video>
            </div>
            <div class="video-txt">
              <div class="video-title-wrap">
                <div>
                  <div class="video-btn" @click="() => (saveVisible = true)">
                  <span class="mr-5">
                    <SaveOutlined />
                  </span>
                  <span>保存至素材库</span>
                </div>
                <MoreButton  :data="{material_url:cropVideoUrl,autoName:video_name}" :excludeNames="['saveToMaterial']"></MoreButton>
                </div>
              </div>
            </div>
          </template>
          <div class="no-video" v-else>
            <img src="../FastVideoGeneration/imgs/privew.webp" />
            <div class="text-gray-5">暂无解析数据</div>
          </div>
        </template>
        <div class="content-loading" v-else>
          <a-skeleton-button
            active
            style="width: 100%; height: 400px"
            block
          ></a-skeleton-button>
          <a-skeleton active></a-skeleton>
        </div>
      </div>
    </div>
  </div>

  <!-- 充值弹窗 -->
  <vipModal :visible="vipVisible" @close="vipVisible = false"></vipModal>
  <MaterialsModule
    ref="materials"
    :material_type="'video'"
    :data="{ material_url: cropVideoUrl, autoName: video_name }"
    @onSuccess="() => (saveVisible = false)"
    :visible="saveVisible"
    @onCancel="saveVisible = false"
  />
  <ChooseMaterial
    :isClip="false"
    material_type="video"
    :visible="chooseVisible"
    @close="closeChoose"
  />
</template>

<script>
import { reactive, toRefs, ref, onUnmounted, computed,watch } from "vue";
import dayjs from "dayjs";
// 充值弹窗
import vipModal from "@/socialMedia/Vip/vipModal.vue";
const vipModalRef = ref(null);
import {
  CloudUploadOutlined,
  PlusOutlined,
  CopyOutlined,
  SaveOutlined,
  DownloadOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import { useRouter } from "vue-router";
import ChooseMaterial from "../EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
import notTextSpeech from "@/views/shotstack/CreationCenter/components/notTextSpeech.vue";
import store from "@/store/index.js";
import utils from "@/common/utils/utils";
import MaterialsModule from "../components/MaterialsModule/materialLibraryModal.vue";
import { message, notification } from "ant-design-vue";
import VideoRemoveSign from "./components/VideoRemoveSign.vue";
import { getComputingPowerDetail, platformList,useModal,useTextToH } from "./utils/index.js";
import MoreButton from "@/views/shotstack/CreationCenter/components/routeToButton.vue";
export default {
  name: "VideoRemoveSignIndex",
  components: {
    CloudUploadOutlined,
    PlusOutlined,
    notTextSpeech,
    ChooseMaterial,
    vipModal,
    MaterialsModule,
    CopyOutlined,
    SaveOutlined,
    DownloadOutlined,
    VideoRemoveSign,
    MoreButton,
  },
  setup() {
    const router = useRouter();
    const state = reactive({
      internetVideoUrl: "",
      radioValue: 1,
      addVisible: false,
      chooseVisible: false,
      currentVideo: {},
      submitLoading: false,
      residue_count: 0,
      debounceTimer: null,
      unit: "",
      name_unit: "",
      consumes: "",
      notVoiceNumDialogRef: null,
      usable: 1,

      useNum: 1,
      saveVisible: false,
      title: "",
      videoUrl: "", //要裁剪的视频的链接
      videoUrl_backup: "",
      cropVideoUrl: "", //裁剪好的视频链接
      btnLoading: false,
      cut_compiled: false,
      cropLoading: false,
      timer: null,
      cropTimer: null,
      pList:platformList,
    });
    let vipVisible = ref(false);
    let video_name = ref("");
    const btnTxt = computed(() => {
      return state.submitLoading ? "提取中，预计耗时20秒" : "开始提取";
    });

    const cancelCrop = () => {
      state.currentVideo = {};
      state.videoUrl = "";
    };
    const copyTitle = () => {
      utils.copyText(state.title);
    };
    watch(()=>store.getters.applicationMaterialData,(data)=>{
      if(Object.keys(data).length){
        state.currentVideo = data
        state.radioValue = 2
        state.videoUrl = data.material_url;
      } 
    },{deep:true,immediate:true})
    const handleCrop = async (crop_box_data) => {
      const res = await getComputingPowerDetail({key:'extract_video_erasure_logo_point'})
      let content = useTextToH({...res,title:'视频擦除标志'})
      useModal({title:'视频擦除标志',res,content}).then(data=>{
        state.cropLoading = true;
        let url = state.videoUrl;
        removeVideoTxt(url, crop_box_data);
      })
    };

    const downloadVideo = async () => {
      const videoUrl = state.cropVideoUrl;
      const filename =
        "视频" + "_" + dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
      const fileUrl = videoUrl;
      state.btnLoading = true;
      let blob = null;
      try {
        const response = await fetch(fileUrl); // 获取视频链接
        blob = await response.blob(); // 将响应转为 Blob
      } catch (e) {
        state.btnLoading = false;
        return message.error("视频下载失败，请稍后再试");
      }

      const url = window.URL.createObjectURL(blob); // 创建一个 blob URL
      const link = document.createElement("a");
      link.href = url; // 设置 href 为 blob URL
      link.download = filename; // 可选，设置下载时的文件名
      document.body.appendChild(link);
      link.click(); // 模拟点击下载
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url); // 清理
      state.btnLoading = false;
    };
    // 开始提取
    const handleExtract = async () => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        vipVisible.value = true;
        return;
      }
      if (state.radioValue == 1) {
        // 网络视频
        if (!state.internetVideoUrl) {
          message.warn("请先粘贴视频链接");
          return;
        }
        add(state.internetVideoUrl);
      } else {
        // 本地视频
        if (!state.currentVideo.material_url) {
          message.warn("请先选择素材库视频");
          return;
        }
        add(state.currentVideo.material_url);
      }
    };
    // 视频提取
    const add = async (text) => {
      state.submitLoading = true;
      let params = {
        source: state.radioValue == 1 ? "internet" : "material",
        text,
        business_type: "extract_video_link_point",
      };
      request
        .post("/work_ai", "/user/socialMedia/videoExtractTask/add", params)
        .then((res) => {
          state.submitLoading = false;
          console.log(res);
          if (res?.code) {
            return message.error(res?.msg);
          }
          queryTask(res.result);
        })
        .catch((err) => {
          state.submitLoading = false;
        });
    };
    // 查询视频提取进度
    const queryTask = async (id) => {
      state.submitLoading = true;
      let params = {
        id,
      };

      state.timer = setInterval(() => {
        request
          .get("/work_ai", "/user/socialMedia/videoExtractTask/detail", params)
          .then((res) => {
            if (res.result.status == 2) {
              state.submitLoading = false;
              state.title = res.result.title;
              state.videoUrl = res.result.video_url;
              video_name.value =
                "视频" +
                "_" +
                dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
              clearInterval(state.timer);
            } else if (res.result.status == 3) {
              state.submitLoading = false;
              clearInterval(state.timer);
              message.error(res.result.status_txt);
            }
          })
          .catch((err) => {
            state.submitLoading = false;
            clearInterval(state.timer);
            message.error(err.message);
          });
      }, 1000);
    };

    const handleOk = () => {
      add();
    };

    const showOpenMaterialModal = () => {
      state.chooseVisible = true;
    };
    const closeChoose = (obj) => {
      console.log(obj, "选择的素材");

      state.chooseVisible = false;
      if (obj) {
        state.currentVideo = obj;
        state.videoUrl = obj.material_url;
      }
    };

    const playVideo = () => {
      document.getElementById("videoPlayer").play();
    };

    const deleteVideo = () => {
      state.currentVideo = {};
      store.dispatch('setApplicationMaterialData',{})
    };

    const getCount = async (data = {}) => {
      const { number = 1, init = false } = data;
      return new Promise(async (resolve, reject) => {
        const res = await request.get(
          "/work_ai",
          "/user/shotstack/video/conver/text/config",
          {
            number,
            key: "extract_video_link_point",
          }
        );
        console.log(res.usable, "res接口传参1231312321");
        state.residue_count = res.pointInfo.current;
        state.consumes = res.pointInfo.consumes;
        state.unit = res.pointInfo.unit;
        state.name_unit = res.pointInfo.name;
        // 剩余次数
        state.useNum = res.pointInfo.current;
        state.usable = res.usable;
        if (res.usable != 1 && !init) {
          vipVisible.value = true;
          reject(false);
          return;
        }
        if (!init) {
          state.usable = res.usable;
          state.notVoiceNumDialogRef.showModal();
          resolve(true);
        }
      });
    };

    getCount({
      number: 1,
      init: true,
    });

    // 防抖
    const debouncedClick = () => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        vipVisible.value = true;
      } else {
        if (state.debounceTimer) {
          clearTimeout(state.debounceTimer);
        }

        state.debounceTimer = setTimeout(() => {
          showOpenMaterialModal();
        }, 500);
      }
    };

    onUnmounted(() => {
      if (state.timeoutId) {
        clearTimeout(state.timeoutId);
        state.timeoutId = null;
      }
      state.timer && clearInterval(state.timer);
      state.cropTimer && clearInterval(state.cropTimer);
      store.dispatch('setApplicationMaterialData',{})
    });

    const jumpPath = (key) => {
      router.push({
        name: key,
      });
    };
    const queryVideoRemoveTxt = (id) => {
      state.cropLoading = true;
      let params = {
        id,
      };

      state.cropTimer = setInterval(() => {
        request
          .get("/work_ai", "/user/socialMedia/videoExtractTask/detail", params)
          .then((res) => {
            if (res.result.status == 2) {
              state.cropLoading = false;
              state.title = res.result.title;
              state.cropVideoUrl = res.result.after_url;
              video_name.value =
                "视频" +
                "_" +
                dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
              clearInterval(state.cropTimer);
            } else if (res.result.status == 3) {
              state.cropLoading = false;
              clearInterval(state.cropTimer);
              message.error(res.result.status_txt);
            }
          })
          .catch((err) => {
            state.cropLoading = false;
            clearInterval(state.cropTimer);
            message.error(err.message);
          });
      }, 1000);
    };
    // 视频擦除字幕
    const removeVideoTxt = (video_url, boxes) => {
      if (store.getters.isVersionExpired) {
        notification.warn({ message: "您的套餐已到期", duration: 2 });
        vipVisible.value = true;
        return;
      }
      state.cropLoading = true;
      let params = {
        source: state.radioValue == 1 ? "internet" : "material",
        video_url,
        boxes,
      };
      if (state.radioValue == 2 && state.currentVideo.oss_media_id) {
        //素材库
        params.oss_media_id = state.currentVideo.oss_media_id;
      }

      request
        .post(
          "/work_ai",
          "/user/socialMedia/videoExtractTask/erasureLogo/add",
          params
        )
        .then((res) => {
          if (res?.code) {
            state.cropLoading = false;
            return message.error(res?.msg);
          }
          queryVideoRemoveTxt(res.result);
        })
        .catch((err) => {
          state.cropLoading = false;
        });
    };
    return {
      ...toRefs(state),
      vipModalRef,
      vipVisible,
      debouncedClick,
      handleOk,
      add,
      showOpenMaterialModal,
      closeChoose,
      handleExtract,
      playVideo,
      deleteVideo,
      btnTxt,
      video_name,
      copyTitle,
      downloadVideo,
      jumpPath,
      cancelCrop,
      handleCrop,
    };
  },
};
</script>

<style lang="less" scoped>
.video-extraction-body {
  display: flex;
  height: calc(100vh - 136px);
  gap: 10px;
}

.video-extraction-left {
  background-color: #fff;
  padding: 20px;
  flex: 1;
  height: 100%;
  overflow-y: scroll;

  // 滚动条
  &::-webkit-scrollbar {
    width: 4px;
    height: 4px;
  }
}

.video-extraction-right {
  background-color: #fff;
  padding: 20px;
  width: 750px;
  height: 100%;
  flex-shrink: 0;
  overflow-y: scroll;

  // 滚动条
  &::-webkit-scrollbar {
    width: 4px;
    height: 4px;
  }
}

.video_con {
  width: 150px;
  height: 250px;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  .operate_con {
    display: none;
  }

  &:hover {
    .operate_con {
      width: 150px;
      height: 250px;
      position: absolute;
      left: 0;
      top: 0;
      background-color: rgba(0, 0, 0, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;

      .play_icon {
        color: #fff;
        font-size: 24px;
        cursor: pointer;

        &:hover {
          color: #ff5652;
        }
      }

      .delete_icon {
        color: #fff;
        font-size: 24px;
        cursor: pointer;

        &:hover {
          color: #ff5652;
        }
      }
    }
  }

  video {
    max-width: 100%;
    max-height: 100%;
  }
}

.smart-clip {
  padding: 14px 14px 0;
  height: 100%;
  box-sizing: border-box;
}

.ant-input-number {
  border-radius: 5px;
}

button {
  border-radius: 5px;
}

:deep(.ant-select-selector) {
  border-radius: 0 5px 5px 0 !important;
}

.textarea-wrapper {
  border-radius: 5px;
}

input {
  border-radius: 5px;
}

:deep(.ant-card) {
  border-radius: 15px;
}

.upload-wrapper {
  width: 200px;
  height: 324px;
  margin: 0 20px 20px 0;
  padding: 20px;
  background-color: #f3f4f6;
  border-radius: 15px;
}

.upload-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 46px;
  width: 160px;
  height: 284px;
  background-color: #fff;
  border-radius: 15px;
  cursor: pointer;
}

.text-16 {
  font-size: 16px;
}

.tip {
  display: flex;
  align-items: center;
  height: 40px;
  margin-left: 70px;
  font-size: 12px;
}

.video-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 400px;
  background-color: #eee;
}

.content-loading {
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
}

:deep(.ss-skeleton-button) {
  width: 100%;
  height: 100%;
}

.video-txt {
  margin-top: 20px;

  .video-name {
    font-weight: 600;
    font-size: 15px;
  }

  .video-title {
    padding: 10px 0;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    font-size: 14px;
  }

  .video-btn {
    display: inline-flex;
    align-items: center;
    cursor: pointer;
    justify-content: center;
    color: var(--ss-primary-color);
    margin-right: 20px;
    font-size: 14px;

    &:hover {
      color: var(--ss-primary-5);
    }
  }

  .download-btn {
    display: flex;
    justify-content: flex-end;
  }
}

.no-video {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
